package org.cms.config;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.cms.util.RUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice("org.cms")
public class ExceptionConfig {

    /**
     * 返回400，请求错误
     */
    @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public RUtil<String> handleBusinessException(Exception e, HttpServletRequest request) {
        log.warn("请求错误:{}，-{}", request.getRequestURI(), e.getMessage());
        return RUtil.fail("请求错误: " + e.getMessage());
    }

    /**
     * 返回422，参数错误
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    public RUtil<String> handleValidationException(Exception e, HttpServletRequest request) {
        log.warn("参数错误：{}，-{}", request.getRequestURI(), e.getMessage());
        return RUtil.fail("参数错误");
    }

    /**
     * 返回500，内部错误
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RUtil<String> handlerException(Exception e, HttpServletRequest request) {
        log.error("内部错误：{}，-{}", request.getRequestURI(), e.getMessage());
        return RUtil.fail("内部错误");
    }

}